package com.yangjie.web.jsf.syslog;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.yangjie.common.dao.criteria.OrderByExpression;
import com.yangjie.common.dao.criteria.PaginationQueryCriteria;
import com.yangjie.common.syslog.SysLog;
import com.yangjie.common.syslog.SysLogService;


public class LazySysLogDataModel extends LazyDataModel<SysLog> {
	Logger logger = Logger.getLogger(this.getClass());
	@Inject
	private SysLogService sysLogService = null;
	private List<SysLog> datasource = null;  
    private PaginationQueryCriteria criteria = null;

    
    
    
	public SysLogService getSysLogService() {
		return sysLogService;
	}

	public void setSysLogService(SysLogService sysLogService) {
		this.sysLogService = sysLogService;
	}

	public PaginationQueryCriteria getCriteria() {
		return criteria;
	}

	public void setCriteria(PaginationQueryCriteria criteria) {
		this.criteria = criteria;
	}

	@Override
	public SysLog getRowData(String rowKey) {
		return (SysLog)sysLogService.get(Integer.parseInt(rowKey));
	}

	@Override
	public Object getRowKey(SysLog log) {
		return log.getId();
	}

	@Override
	public List<SysLog> load(int first, int pageSize, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {
		logger.debug("lazy load datamodel loading...first:" + first);
		long count = sysLogService.count(criteria);
		if(first > count) {
			first = (int)((count / pageSize) * pageSize);
		}
		if(sortField != null) {
			criteria.getCriteria().clearOrder();
			if(sortOrder == SortOrder.ASCENDING) {
				criteria.getCriteria().addOrderByExpression(new OrderByExpression(sortField, OrderByExpression.ORDER_ASC));
			} else {
				criteria.getCriteria().addOrderByExpression(new OrderByExpression(sortField, OrderByExpression.ORDER_DESC));
			}
		}
		criteria.setPageSize(pageSize);
		criteria.setFirstRow(first);
		this.datasource = sysLogService.find(criteria);
		this.setRowCount((int)count);
		return datasource;

	}
}
